from interface.widget import Page, scale, YScrollableContainer
from tkinter import ttk
import tkinter
from utils.network import request
from utils import memory
from tkinter import messagebox


class MultiSendPage(Page):

    def __init__(self, master):
        Page.__init__(self, master)
        self.account2is_select = {}

    def content(self, master):
        back_button = ttk.Button(master, text='返回', command=self.master.close_page)
        back_button.place(**scale(x=40, y=30, width=80, height=30))

        ttk.Style().configure('MultiSendPage.TitleLabel.TLabel', anchor='center', font=('', 14))
        title_label = ttk.Label(master, text='群发消息', style='MultiSendPage.TitleLabel.TLabel')
        title_label.place(**scale(relx=0.5, x=-80, y=30, width=160, height=30))

        text_entry = tkinter.Text(master)
        text_entry.place(**scale(relx=0.4, y=80, relwidth=0.6, width=-40, relheight=1, height=-100))

        def send_button_method():
            recipients = []
            for account in self.account2is_select.keys():
                if self.account2is_select[account].get():
                    recipients.append(account)
            text = text_entry.get('1.0', tkinter.END)
            if text[-1] == '\n':
                text = text[: -1]
            res = request('/message/send', {
                'recipients': recipients,
                'text': text
            })
            messagebox.showinfo('发送成功', '群发消息已发送给选定的用户')
            self.master.close_page()
            for message in res['messages']:
                memory.add_message(message)

        send_button = ttk.Button(master, text='发送', command=send_button_method)
        send_button.place(**scale(relx=1, x=-120, y=30, width=80, height=30))

        user_select_container = YScrollableContainer(master)
        user_select_container.x = 40
        user_select_container.y = 80
        user_select_container.relwidth = 0.4
        user_select_container.width = -80
        user_select_container.relheight = 1
        user_select_container.height = -100
        user_select_container.display()

        for user in memory.users.values():
            var = tkinter.BooleanVar()
            check_button = ttk.Checkbutton(user_select_container.inner.tkw, variable=var, text='{} ({})'.format(
                user['username'], user['account']
            ))
            check_button.place(**scale(x=0, y=30*len(self.account2is_select), relwidth=1, height=30))
            self.account2is_select[user['account']] = var
            user_select_container.update()
